<template>
  <div class="privacy-setting-form">
    <!-- 版本提示 -->
    <el-alert v-if="props.privacyVersion === 2" title="开发版本提醒" type="warning" :closable="false" class="mb-4">
      <template #default>
        <div>当前正在编辑<strong>开发版本</strong>的隐私协议配置，修改后需要重新提交审核才能生效。</div>
        <div>当前自定义隐私协议感觉有些问题，尽可能不使用自定义</div>
      </template>
    </el-alert>
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" class="mt">
      <!-- 隐私协议配置 -->
      <div class="mb-6">
        <div class="flex justify-between items-center mb-4">
          <h4 class="text-base font-medium">隐私协议配置</h4>
          <el-button v-if="hasRecommendedConfig" type="success" size="small" @click="onUseRecommendedConfig">
            <el-icon class="mr-1"><Star /></el-icon>
            使用推荐配置
          </el-button>
        </div>
        <dk-minapp-privacy-setting v-model="formData.setting_list" :privacy-options="privacyOptions" title="" class="mt" />
      </div>

      <!-- 联系方式配置 -->
      <div class="mb-6">
        <h4 class="text-base font-medium mb-4">联系方式（至少填写一种）</h4>
        <div class="grid grid-cols-2 gap-4">
          <el-form-item label="联系电话" prop="contact_phone">
            <el-input v-model="formData.contact_phone" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="联系邮箱" prop="contact_email">
            <el-input v-model="formData.contact_email" placeholder="请输入联系邮箱" />
          </el-form-item>
          <el-form-item label="联系QQ" prop="contact_qq">
            <el-input v-model="formData.contact_qq" placeholder="请输入联系QQ" />
          </el-form-item>
          <el-form-item label="联系微信" prop="contact_weixin">
            <el-input v-model="formData.contact_weixin" placeholder="请输入联系微信" />
          </el-form-item>
        </div>
      </div>

      <!-- 通知方式 -->
      <div class="mb-6">
        <h4 class="text-base font-medium mb-4">通知方式</h4>
        <el-form-item label="通知方式" prop="notice_method" required>
          <el-input
            v-model="formData.notice_method"
            type="textarea"
            :rows="3"
            placeholder="请填写当开发者收集信息有变动时，通过该方式通知用户的具体方式，例如：通过弹窗、公告或其他方式"
            maxlength="200"
            show-word-limit
          />
          <div class="text-sm text-gray-500 mt-2">请按照实际情况填写，例如：通过弹窗或者公告或者其他方式</div>
        </el-form-item>
      </div>
    </el-form>

    <!-- 操作按钮 -->
    <div class="text-center space-x-4">
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="onSubmit">
        {{ submitting ? '提交中...' : props.privacyVersion === 2 ? '更新开发版本' : '确定更新' }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

defineOptions({
  name: 'PrivacySettingForm'
})

// Props
const props = defineProps({
  initialData: {
    type: Object,
    default: () => ({})
  },
  templateData: {
    type: Object,
    default: () => ({})
  },
  privacyVersion: {
    type: Number,
    default: 1
  }
})

// Emits
const emit = defineEmits(['submit', 'cancel'])

// 表单引用
const formRef = ref(null)
const submitting = ref(false)

// 表单数据
const formData = ref({
  setting_list: [],
  contact_phone: '',
  contact_email: '',
  contact_qq: '',
  contact_weixin: '',
  notice_method: ''
})

// 隐私选项（从API数据中提取）
const privacyOptions = computed(() => {
  if (!props.initialData?.privacy_desc?.privacy_desc_list) return {}

  const options = {}
  props.initialData.privacy_desc.privacy_desc_list.forEach((item) => {
    options[item.privacy_key] = item.privacy_desc
  })
  return options
})

// 是否有推荐配置
const hasRecommendedConfig = computed(() => {
  return props.templateData?.config?.privacy_setting_list && props.templateData.config.privacy_setting_list.length > 0
})

// 推荐配置数据
const recommendedConfig = computed(() => {
  return props.templateData?.config?.privacy_setting_list || []
})

// 表单验证规则
const rules = {
  notice_method: [{ required: true, message: '请填写通知方式', trigger: 'blur' }]
}

// 自定义联系方式验证
const validateContact = () => {
  const { contact_phone, contact_email, contact_qq, contact_weixin } = formData.value
  return contact_phone || contact_email || contact_qq || contact_weixin
}

// 初始化数据
const initData = () => {
  if (props.initialData) {
    // 初始化隐私设置列表
    formData.value.setting_list = props.initialData.setting_list || []

    // 初始化联系方式
    const ownerSetting = props.initialData.owner_setting || {}
    formData.value.contact_phone = ownerSetting.contact_phone || ''
    formData.value.contact_email = ownerSetting.contact_email || ''
    formData.value.contact_qq = ownerSetting.contact_qq || ''
    formData.value.contact_weixin = ownerSetting.contact_weixin || ''
    formData.value.notice_method = ownerSetting.notice_method || ''
  }
}

// 提交表单
const onSubmit = async () => {
  try {
    // 验证表单
    await formRef.value.validate()

    // 验证联系方式
    if (!validateContact()) {
      ElMessage.warning('请至少填写一种联系方式')
      return
    }

    // 验证隐私设置
    if (!formData.value.setting_list || formData.value.setting_list.length === 0) {
      ElMessage.warning('请至少配置一项隐私设置')
      return
    }

    // 检查隐私设置的完整性
    const incompleteItems = formData.value.setting_list.filter(
      (item) => !item.privacy_key || !item.privacy_key.trim() || !item.privacy_text || !item.privacy_text.trim()
    )

    if (incompleteItems.length > 0) {
      ElMessage.warning('请完善所有隐私设置的类型和用途信息')
      return
    }

    submitting.value = true

    // 构造提交数据
    const submitData = {
      setting_list: formData.value.setting_list.map((item) => ({
        privacy_key: item.privacy_key.trim(),
        privacy_text: item.privacy_text.trim()
      })),
      owner_setting: {
        contact_phone: formData.value.contact_phone.trim(),
        contact_email: formData.value.contact_email.trim(),
        contact_qq: formData.value.contact_qq.trim(),
        contact_weixin: formData.value.contact_weixin.trim(),
        notice_method: formData.value.notice_method.trim()
      }
    }

    console.log('提交隐私协议数据:', submitData)

    // 发送提交事件
    emit('submit', submitData)

    ElMessage.success('隐私协议配置已准备完成')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

// 取消操作
const onCancel = () => {
  emit('cancel')
}

// 使用推荐配置
const onUseRecommendedConfig = () => {
  if (!hasRecommendedConfig.value) {
    ElMessage.warning('暂无推荐配置')
    return
  }

  ElMessageBox.confirm(
    `确定要使用推荐配置吗？这将覆盖当前的隐私协议配置。\n推荐配置包含 ${recommendedConfig.value.length} 项隐私设置。`,
    '使用推荐配置',
    {
      confirmButtonText: '确定使用',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      // 使用推荐配置覆盖当前配置
      formData.value.setting_list = [...recommendedConfig.value]
      ElMessage.success('已应用推荐配置')
    })
    .catch(() => {
      // 用户取消
    })
}

// 组件挂载时初始化数据
onMounted(() => {
  initData()
})
</script>

<style scoped>
.privacy-setting-form {
  padding: 20px;
}
</style>
